import { BaseService, CoolCommException } from "@cool-midway/core";
import { Inject, Provide } from "@midwayjs/core";
import { InjectEntityModel } from "@midwayjs/typeorm";
import { Equal, Not, Repository } from "typeorm";
import { ProviderTeamJoinEntity } from "../entity/join";
import { ProviderTeamEntity } from "../entity/team";
import { Context } from "@midwayjs/koa";
import { CommonAuditStatus } from "../../../interface";
import { ProviderProfileEntity } from "../entity/profile";
import { CapacityEntity } from "../../transport/entity/capacity";
import { AuditJoinRequestDTO, JoinRequestDTO } from "../dto/join";

@Provide()
export class ProviderTeamJoinService extends BaseService {

    @InjectEntityModel(ProviderTeamJoinEntity)
    providerTeamJoinEntity: Repository<ProviderTeamJoinEntity>

    @InjectEntityModel(ProviderTeamEntity)
    providerTeamEntity: Repository<ProviderTeamEntity>

    @InjectEntityModel(ProviderProfileEntity)
    providerProfileEntity: Repository<ProviderProfileEntity>

    @InjectEntityModel(CapacityEntity)
    capacityEntity: Repository<CapacityEntity>

    @Inject()
    ctx: Context

    async joinRequest(dto: JoinRequestDTO) {
        const { inviteCode } = dto || {};
        if (!inviteCode) {
            throw new CoolCommException('团队邀请码不能为空')
        }
        const team = await this.providerTeamEntity.findOne({
            where: { inviteCode: Equal(inviteCode), ownerProviderId: Not(Equal(this.ctx.provider.id)) }
        })
        if (!team) {
            throw new CoolCommException('团队邀请码不存在或已失效')
        }
        const joinRequest = await this.providerTeamJoinEntity.findOne({
            where: { providerId: Equal(this.ctx.provider.id), teamId: Equal(team.id) }
        })
        // 已有申请记录
        if (joinRequest) {
            // 待审核直接提示
            if (joinRequest.status === CommonAuditStatus.PENDING) {
                throw new CoolCommException('已提交申请，请等待审核')
            }
            // 已通过不允许重复申请
            if (joinRequest.status === CommonAuditStatus.APPROVED) {
                throw new CoolCommException('您已加入该团队或申请已通过')
            }
            // 拒绝状态，允许重新发起，将状态置为待审核
            await this.providerTeamJoinEntity.update(joinRequest.id, {
                status: CommonAuditStatus.PENDING,
            })
            return true
        }

        // 无申请记录，创建新的待审核请求
        await this.providerTeamJoinEntity.save({
            providerId: this.ctx.provider.id,
            teamId: team.id,
            status: CommonAuditStatus.PENDING,
        })
        return true
    }

    /**
     * 审核加入团队请求
     * @param joinId 申请ID
     * @param approve 是否通过
     */
    async auditJoinRequest(dto: AuditJoinRequestDTO) {
        const { joinId, approve, rejectReason } = dto || ({} as AuditJoinRequestDTO);
        if (!joinId && joinId !== 0) {
            throw new CoolCommException('缺少申请标识')
        }
        return await this.providerTeamJoinEntity.manager.transaction(async (manager) => {
            const join = await manager.findOne(ProviderTeamJoinEntity, { where: { id: Equal(joinId) } })
            if (!join) {
                throw new CoolCommException('申请记录不存在')
            }
            // 校验审核权限：只能审核自己团队的申请
            const team = await manager.findOne(ProviderTeamEntity, { where: { id: Equal(join.teamId), ownerProviderId: Equal(this.ctx.provider.id) } })
            if (!team) {
                throw new CoolCommException('无权限审核该申请')
            }
            if (join.status !== CommonAuditStatus.PENDING) {
                throw new CoolCommException('该申请已处理')
            }

            if (!approve) {
                await manager.update(ProviderTeamJoinEntity, { id: join.id }, { status: CommonAuditStatus.REJECTED, rejectReason })
                return true
            }

            // 通过：将申请人的运力关联到该团队
            const profile = await manager.findOne(ProviderProfileEntity, { where: { providerId: Equal(join.providerId) } })
            if (!profile) {
                throw new CoolCommException('申请人资料不存在')
            }
            const res = await manager.update(CapacityEntity, { id: profile.capacityId }, { teamId: team.id })
            if (!res.affected) {
                throw new CoolCommException('运力信息更新失败')
            }
            await manager.update(ProviderTeamJoinEntity, { id: join.id }, { status: CommonAuditStatus.APPROVED })
            return true
        })
    }
}